package com.ty.zls.components;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;

public class MyReceycleView extends RecyclerView {

    public MyReceycleView(@NonNull Context context) {
        super(context);
    }

    public MyReceycleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyReceycleView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 当数据为空时展示的View
     */
    private View mEmptyView;

    private SwipeToLoadLayout layout;

    /**
     * 创建一个观察者
     */
    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {
        @Override
        public void onChanged() {
            Adapter<?> adapter = getAdapter();
            if (adapter != null && mEmptyView != null) {
                if (adapter.getItemCount() == 0) {
                    mEmptyView.setVisibility(View.VISIBLE);
                    layout.setVisibility(View.GONE);
                } else {
                    mEmptyView.setVisibility(View.GONE);
                    layout.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    /**
     * * @param emptyView 展示的空view
     */
    public void setEmptyView(View emptyView) {
        mEmptyView = emptyView;
    }

    public View getmEmptyView() {
        return mEmptyView;
    }

    public SwipeToLoadLayout getLayout() {
        return layout;
    }

    public void setLayout(SwipeToLoadLayout layout) {
        this.layout = layout;
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
        if (adapter != null) {
            //这里用了观察者模式，同时把这个观察者添加进去，
            adapter.registerAdapterDataObserver(emptyObserver);
        }
        emptyObserver.onChanged();
    }
}

